<%@ page import="org.ifilm.model.*,org.ifilm.util.GeneralConstants"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!-- %@page import="org.ifilm.util.GeneralConstants"%>  -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Create Project</title>
		
		<link rel="icon" type="image/png" href="/film/img/favicon.ico">
		<link href="/film/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />
		<script src="/film/js/jquery.js"></script>
		<script src="/film/bootstrap/js/bootstrap.min.js"></script>
        <script src="/film/js/photoUpload.js"></script>
        
		<style>
			/* 60px to make the container go all the way to the bottom of the topbar */
			body {
				padding-top: 60px;
			}
			.number {
				width : 100px;
			}
			.long-text {
				width : 350px;
			}
			#dummy-placeholder {
				height : 100px;
			}
		</style>
	</head>
	<body>
		<!-- this area is used for the navigation bar -->
		<!-- where the navigation bar has ifilm home create project sections -->
		<jsp:include page="navigationBar.jsp"/>	
		<!-- In this part, we will get project(film) properties from user such as -->
		<!-- project name, filming location, film subject, language -->
		<!-- start date and estimated shooting time -->
		<div class="container">
			<form id="postForm">
				<table class="table table-condensed">
					<!-- in this row we get project name -->
					<tr>
						<td>Project Name:</td>
						<td><input type="text" name="<%=GeneralConstants.projectName%>"></td>
						
						<td rowspan="4">
							<input type="hidden" id="thumbnailUrl" name="<%=GeneralConstants.projectThumbnailUrl%>" value="">
							<a href="#" id="uploadPhoto">
				 				<img class="media-object" id="thumbnail" style="height:170px;width:200px;" src="http://placehold.it/250x200">
				 			</a>
				 			
				 			<input type="file" name="fileData" id="image_file"/>
				 		</td>
					</tr>
					<!-- in this row we get filming location -->
					<!-- location will be specified as country and city -->
					<tr>
						<td>Filming Location:</td>
						<td>
							<div class="control-group">
						       	<div class="controls">
						         	<select id="country" name="<%=GeneralConstants.projectCountry%>">
						         		<option value="">Choose a Country</option>
						         	</select>
						         	</br>
						         	<select id="city" style="display:none;" name="<%=GeneralConstants.projectCity%>">
						         		
						         	</select>
						     	</div>
						    </div>				
						</td>
						<td></td>
					</tr>
					
					<!-- in this row we get film subject -->
					<tr>
						<td>Film Subject:</td>
						<td>
							<input type="text" name="<%=GeneralConstants.projectSubject%>">
						</td>
						<td></td>
					</tr>
					<!-- in this row we get language of the film -->
					<tr>
						<td>Language:</td>
						<td>
							<div class="control-group">
						       	<div class="controls">
						         	<select id="language" name="<%=GeneralConstants.projectLanguage%>">
						         		<option value="">Choose a Language</option>
						         	</select>
					         	</div>
				         	</div>
						</td>
						<td></td>
					</tr>
					<!-- in this row we get start time of the film -->
					<!-- this will be in the format day month year -->
					<tr>
						<td>Filming start date:</td>
						<td>
							<input type="date" name="<%=GeneralConstants.projectStartDate%>"></input>
						</td>
						<td></td>
					</tr>
	
					<!-- in this row we get the estimated release date of the project(film) -->
					<tr>
						<td>Estimated Release Date:</td>
						<td>
							<input type="date" name="<%=GeneralConstants.projectReleaseDate%>"></input>
						</td>
						<td></td>
					</tr>
	
					<tr>
						<td>Description:</td>
						<td colspan=2><textarea rows="5" class="long-text"
							name="<%=GeneralConstants.projectDescription%>"></textarea>
						</td>					
					</tr>
					<tr>
						<td colspan=3>
							<a href="#myModal" role="button" class="btn" data-toggle="modal">Add posting</a>
							<jsp:include page="jobPostings.jsp"/>						
						</td>
					</tr>
					<tr>
						<td colspan=3><button class="btn" id="createProject" type="submit">Create</button></td>
					</tr>
				</table>
			</form>
		</div>
	</body>	
	
	<script type="text/javascript">
	
		//TODO move these scripts in a js file
		
		var userIds = ['<%=GeneralConstants.jobPostingActor%>',
		               '<%=GeneralConstants.jobPostingActress%>',
		               '<%=GeneralConstants.jobPostingDublour%>', 
		               '<%=GeneralConstants.jobPostingProducer%>', 
		               '<%=GeneralConstants.jobPostingSupervisor%>', 
		               '<%=GeneralConstants.jobPostingProductionManager%>', 
		               '<%=GeneralConstants.jobPostingProductionCoordinator%>', 
		               '<%=GeneralConstants.jobPostingDirectorOfPhotography%>', 
		               '<%=GeneralConstants.jobPostingCameraman%>', 
		               '<%=GeneralConstants.jobPostingCostumeDesigner%>', 
		               '<%=GeneralConstants.jobPostingMakeupArtist%>', 
		               '<%=GeneralConstants.jobPostingHairDresser%>', 
		               '<%=GeneralConstants.jobPostingArtDirector%>', 
		               '<%=GeneralConstants.jobPostingSetDecorator%>', 
		               '<%=GeneralConstants.jobPostingConstructionCoordinator%>', 
		               '<%=GeneralConstants.jobPostingSoundMixer%>',
		               '<%=GeneralConstants.jobPostingBoomOperator%>',
		               '<%=GeneralConstants.jobPostingKeyGrip%>',
		               '<%=GeneralConstants.jobPostingEditor%>',
		               '<%=GeneralConstants.jobPostingColorist%>',
		               '<%=GeneralConstants.jobPostingOther%>'
		               ];
		
		var equipmentIds = ['<%=GeneralConstants.equipmentPosting%>'];
		
		$('.dropdown-toggle').dropdown();
		$(".collapse").collapse();
		
		$.ajax("/film/util/getCountries.do").done(function(data) {
			if (data && data.countryList) {
				$.each(data.countryList, function(key, cur) {
					var option = $("<option countyId='" + cur.id + "' value='" + cur.countryName + "'></option>");
					
					option.append(cur.countryName);
					
					$("#country").append(option);
				});
			}
		});
		
		$.ajax("/film/util/getLanguages.do").done(function(data) {
			if (data && data.languageList) {
				$.each(data.languageList, function(key, cur) {
					var option = $("<option value='" + cur.languageName + "'></option>");
					
					option.append(cur.languageName);
					
					$("#language").append(option);
				});
			}
		});
		
		$("#country").change(function() {
			var countryId = $("#country option:selected").attr("countyId");
			
			if (countryId != "") {
				$('#city').find('option').remove();
				
				$.ajax("/film/util/getCitiesByCountryId.do?countryId=" + countryId).done(function(data) {
					$("#city").append("<option value=''>Choose a City</option>");
					if (data && data.cityList) {
						$.each(data.cityList, function(key, cur) {
							var option = $("<option value='" + cur.cityName + "'></option>");
							
							option.append(cur.cityName);
							
							$("#city").append(option);
						});
					}
					
					$("#city").show();
				});
			} else {
				$("#city").hide();
			}
		});
		
		function getXMLHttpRequest() {
	        if (window.XMLHttpRequest) {
	            return new window.XMLHttpRequest;
	        } else {
	            try {
	                return new ActiveXObject("MSXML2.XMLHTTP.3.0");
	            } catch (e) {
	                return null;
	            }
	        }
	    }
		
		$("#image_file").change(function() {
			fileSelected('thumbnail', 'image_file');
			
			var $this = $(this);
			
			var file = $this[0].files[0];
		     
	        var xhr = getXMLHttpRequest();
	        var url = "/film/photo/upload.do";
	        xhr.open("POST", url, true);
	        
	        var formdata = new FormData();
	        formdata.append("fileData", file, "file.jpg");
	        
	        xhr.onreadystatechange = function () {
	            if (xhr.readyState === 4) {
	                if (xhr.status === 200) {
	                    var response = JSON.parse(xhr.response);
	                    if (response.fileName) {
	                        $("#thumbnailUrl").val(response.fileName);
	                    } else {
	                    	alert("Server error");
	                    }
	                } else {
	                	alert("Cannot upload this image!");
	                }
	            }
	        };
	        
	        xhr.ontimeout = function () {
	            onfail("request timeout");
	        };
	        
	        xhr.send(formdata);
		});
		
		$(".modal .inp").blur(function() {
			var $this = $(this);
			if ($this.attr("verify") != "true") {
				$this.attr("verify", "true");
				
				var iconOk = $("<img src='/film/img/icon-ok.jpg' class='onVerifyImages'></img>");
				var iconRemove = $("<i class='icon-remove pull-right removePost onVerifyImages'></i>");
				$this.parent().append(iconRemove).append(iconOk);
			}
		});
		
		$(".removePost").live("click", function() {
			var $this = $(this);
			
			$this.prev().attr("verify", "false");
			$this.next().remove();
			$this.remove();
		});
		
		function resetModal() {
			$('.onVerifyImages').remove();
			$("#dummy-placeholder").css("display", "block");
			$(".nav.nav-tabs").css("display", "block");
			$('.tab-pane').removeClass('active');
			$('li').removeClass('active');
			$('.inp').val('');
		}
		
		postingArray = new Array();
		
		$('#addJob').click(function() {
			$.each($(".modal .tab-pane.active"), function() {
				var divId = $(this).attr("id");
				var posting = {};
				
				if ($.inArray(divId, userIds) != -1) {
					posting["post"] = "user";
					
					var anyAttributeFound = false;
					
					$.each($(".modal #" + divId + " .inp"), function() {
						anyAttributeFound = true;
						posting[$(this).attr("title")] = $(this).val();
						// to reset the input areas and remove the verified icons
						$(this).attr("verify", "false");
					});
					
					if (anyAttributeFound) {
						posting["type"] = divId;
						postingArray.push(posting);
					}
				} else if ($.inArray(divId, equipmentIds) != -1) {
					posting["post"] = "equipment";
					
					var anyAttributeFound = false;
					
					$.each($(".modal #" + divId + " .inp"), function() {
						anyAttributeFound = true;
						posting[$(this).attr("title")] = $(this).val();
						// to reset the input areas and remove the verified icons
						$(this).attr("verify", "false");
					});
					
					if (anyAttributeFound) {
						posting["type"] = divId;
						postingArray.push(posting);
					}
				}
			});
			
			resetModal();
			console.log(postingArray);
		});
		
		$("#postForm").on("submit", function() {
	        $.ajax({
	            url : "/film/project/createProject.do",
	            data : $(this).serialize(),
	            success : function(data) {
					if (data && data.projectId) {
						createPostings(data.projectId);
					} else {
						alert("Error on response");
					}
				},
				error : function(data) {
					alert("Couldn't create project");
				}
	        });
	        
	        return false;
	    });
		
		function createPostings(projectId) {
			var postingData = {};
			
			postingData["projectId"] = projectId;
			postingData["postingData"] = postingArray;
			
			$.ajax({
				url : "/film/notice/createPosting.do",
				data : {data : JSON.stringify(postingData)},
				success : function(data) {
					alert("Successful");
					window.location.href = "/film/project/listProjects.do?page=1&max=2";
				},
				error : function(data) {
					alert(data.responseText);
				}
			});
		}
		
		$('#myModal').on('hide', function() {
			resetModal();
		});
		
		$('#myModal').on('show', function() {			
			$('.model-menu').click( function() { 
				$("#dummy-placeholder").css("display", "none");
			});		
		});
	</script>
	
	<script src="/film/js/commonScripts.js"></script>
</html>